package com.gurumades.jsonform.server.forms.dispatch.handlers;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Random;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.gurumades.jsonform.server.forms.dispatch.DispatchUtil;
import com.gurumades.jsonform.server.forms.dispatch.FormProvider;
import com.gurumades.jsonform.shared.dispatch.GetFormAction;
import com.gurumades.jsonform.shared.dispatch.GetFormResult;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.DispatchException;

public class GetFormHandler implements ActionHandler<GetFormAction, GetFormResult>{

	private JsonParser parser;
	
	@Override
	public Class<GetFormAction> getActionType() {
		return GetFormAction.class;
	}

	@SuppressWarnings({ "serial", "deprecation" })
	@Override
	public GetFormResult execute(GetFormAction action, ExecutionContext context)
			throws DispatchException {
		
		Long buildID = null;
		String formID = action.getFormID();
		FormProvider provider = DispatchUtil.getFormProviders().get(action.getFormID());
		
		if (provider == null) {
			throw new DispatchException("No such form found") {
			};
		}
		
		String str = provider.getForm(formID);
		try {
			ObjectMapper m = new ObjectMapper();
			JsonFactory factory = m.getJsonFactory();
			parser = factory.createJsonParser(new StringReader(str));
			JsonNode form = parser.readValueAsTree();
			
			buildID = new Random().nextLong();
			form = DispatchUtil.preprocessForm(formID, form, true, action.getBuildParams(), buildID);
			StringWriter writter = new StringWriter();
			m.writeValue(writter, form);
			str = writter.toString();
			//System.out.println(str);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) { 
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return new GetFormResult(str, buildID);
	}

	@Override
	public void rollback(GetFormAction action, GetFormResult result,
			ExecutionContext context) throws DispatchException {
		
	}

}
